package leetCode;

/**
 * @PackageName: leetCode
 * @ClassName: LeetCode82
 * @Author: chen jinxu
 * @Date: 2022/3/1 22:39
 * 给定一个已排序的链表的头 head ， 删除原始链表中所有重复数字的节点，只留下不同的数字 。返回 已排序的链表
 * 输入：head = [1,2,3,3,4,4,5]
 * 输出：[1,2,5]
 * 输入：head = [1,1,1,2,3]
 * 输出：[2,3]
 */
public class LeetCode82 {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(3,
                new ListNode(4, new ListNode(4, new ListNode(5)))))));
        ListNode listNode1 = deleteDuplicates(listNode);
        System.out.println(listNode1);
    }
    public static ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return head;
        }
        // 避免链表头被删除
        ListNode dummy = new ListNode(0, head);
        ListNode cur = dummy;
        while (cur.next != null && cur.next.next!= null) {
            if (cur.next.val == cur.next.next.val) {
                int x = cur.next.val;
                while (cur.next != null && cur.next.val == x) {
                    cur.next = cur.next.next;
                }
            } else {
                cur = cur.next;
            }
        }
        return dummy.next;
    }
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
